package cn.kduck.code.generate.web;

import cn.kduck.code.generate.service.GenerateService;
import cn.kduck.code.generate.service.GenerateService.GenerateType;
import cn.kduck.code.generate.service.impl.CodeGenProgressListenerImpl.CodeGenProgress;
import cn.kduck.code.module.service.Module;
import cn.kduck.code.module.service.ModuleService;
import cn.kduck.core.web.json.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/code/generate")
public class GenerateController {

    @Autowired
    private GenerateService generateService;

    @Autowired
    private ModuleService moduleService;

    @Value("${kduck.code.gen-base-path}")
    private String genBasePath;

    @PostMapping
    public JsonObject generate(@RequestParam("types") String[] types, @RequestParam("moduleId") String moduleId, @RequestParam(value = "prompt",required = false)  String prompt, HttpServletResponse response) {
        GenerateType[] generateTypes = new GenerateType[types.length];
        for (int i = 0; i < types.length; i++) {
            generateTypes[i] = GenerateType.valueOf(types[i].toUpperCase());
        }
        generateService.generate(generateTypes, moduleId, prompt);
        return JsonObject.SUCCESS;
    }

    @GetMapping("/progress")
    public JsonObject getGenerateProgress(@RequestParam("moduleId") String moduleId) {
        List<CodeGenProgress> generateProgress = generateService.getGenerateProgress(moduleId);
        return new JsonObject(generateProgress);
    }


    @GetMapping("/download")
    public void downloadCode(@RequestParam("moduleId") String moduleId,HttpServletResponse response) {
//        Module module = moduleService.getModule(moduleId);
//        genBasePath = genBasePath.endsWith(File.separator) ? genBasePath: genBasePath + File.separator;
//        genBasePath = genBasePath + module.getPackageName().replaceAll("[.]","\\" + File.separator);
        File file = new File(genBasePath, moduleId);
        try {
            if(!file.exists()){
                file.mkdirs();
            }
            generateService.zipCodeFiles(file.getPath(), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("打包源码失败：" + file.getPath(),e);
        }
    }
}
